package com.vend.common.base
import android.content.Intent
import android.os.Build
import android.util.Log
import android.view.ViewGroup
import android.webkit.WebResourceRequest
import android.webkit.WebView
import androidx.annotation.ColorInt
import androidx.annotation.RequiresApi
import com.just.agentweb.*
import com.vend.common.mvp.IPresenter

/**
 * Created by glendal on 2022/01/17.
 * 使用BaseWebFragment
 */
abstract class BaseWebFragment<T : IPresenter>: BaseFragment<T>() {
    protected var mAgentWeb: AgentWeb? = null
    private var mMiddleWareWebChrome: MiddlewareWebChromeBase? = null
    private var mMiddleWareWebClient: MiddlewareWebClientBase? = null
    private val mAgentWebUIController: AgentWebUIControllerImplBase? = null
    override fun lazyInit() {
        Log.e("tag","agentLazy")
        if (mAgentWeb != null)
            return
        Log.e("tag","agentInit")
        mAgentWeb = AgentWeb.with(this)
            .setAgentWebParent(
                getAgentWebParent(),
                ViewGroup.LayoutParams(
                    ViewGroup.LayoutParams.MATCH_PARENT,
                    ViewGroup.LayoutParams.MATCH_PARENT
                )
            )
            .useDefaultIndicator(getIndicatorColor(), getIndicatorHeight())
            .setWebLayout(getWebLayout())
            .setAgentWebWebSettings(getAgentWebSettings())
            .setWebViewClient(getWebViewClient())
            .setPermissionInterceptor(getPermissionInterceptor())
            .setWebChromeClient(getWebChromeClient())
            .interceptUnkownUrl()
//                //头部注册实现
//            .additionalHttpHeader()
            .setOpenOtherPageWays(DefaultWebClient.OpenOtherPageWays.ASK)
            .setSecurityType(AgentWeb.SecurityType.STRICT_CHECK)
            .setAgentWebUIController(getAgentWebUIController())
            .setMainFrameErrorView(R.layout.agentweb_error_page, -1)
            .useMiddlewareWebChrome(getMiddleWareWebChrome())
            .useMiddlewareWebClient(getMiddleWareWebClient())
            .createAgentWeb() //
            .ready() //
            .go(getUrl())
    }

    /**
     * 标题的加载逻辑处理
     */
    open fun setTitle(view: WebView?, title: String?) {
        Log.e("tag", " title $title" )
    }

    abstract fun shouldLoadingUrl( view : WebView?,  request : WebResourceRequest?) : Boolean

    protected open fun getAgentWebUIController(): AgentWebUIControllerImplBase? {
        return mAgentWebUIController
    }


    override fun onPause() {
        if (mAgentWeb != null) {
            mAgentWeb!!.webLifeCycle.onPause()
        }
        super.onPause()
    }

    override fun onResume() {
        if (mAgentWeb != null) {
            mAgentWeb!!.webLifeCycle.onResume()
        }
        super.onResume()
    }


    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
    }


    protected open fun getUrl(): String? {
        return ""
    }

    override fun onDestroy() {
        if (mAgentWeb != null) {
            mAgentWeb!!.webLifeCycle.onDestroy()
        }
        super.onDestroy()
    }

    protected open fun getAgentWebSettings(): IAgentWebSettings<*>? {
        return AgentWebSettingsImpl.getInstance()
    }

    protected open fun getWebChromeClient(): WebChromeClient? {
        return object : WebChromeClient(){
            override fun onReceivedTitle(view: WebView?, title: String?) {
                super.onReceivedTitle(view, title)
                setTitle(view,title)
            }

        }

    }

    protected abstract fun getAgentWebParent(): ViewGroup

    @ColorInt
    protected open fun getIndicatorColor(): Int {
        return -1
    }

    protected open fun getIndicatorHeight(): Int {
        return -1
    }

    protected open fun getWebViewClient(): WebViewClient? {
        return object : WebViewClient(){
            @RequiresApi(Build.VERSION_CODES.LOLLIPOP)
            override fun shouldOverrideUrlLoading(
                view: WebView?,
                request: WebResourceRequest?
            ): Boolean {
                Log.e("tag","loading urls  ${request?.url?.toString()}")
                if (shouldLoadingUrl(view,request)){
                    return true
                }
                return super.shouldOverrideUrlLoading(view, request)
            }
        }
    }

    protected open fun getWebView(): WebView? {
        return null
    }

    protected open fun getWebLayout(): IWebLayout<*, *>? {
        return null
    }

    protected open fun getPermissionInterceptor(): PermissionInterceptor? {
        return null
    }

    open fun getMiddleWareWebChrome(): MiddlewareWebChromeBase {
        return object : MiddlewareWebChromeBase() {
            override fun onReceivedTitle(view: WebView, title: String) {
                super.onReceivedTitle(view, title)
                setTitle(view, title)
            }
        }.also { mMiddleWareWebChrome = it }
    }

   open fun getMiddleWareWebClient(): MiddlewareWebClientBase {
        return object : MiddlewareWebClientBase() {
        }.also { mMiddleWareWebClient = it }
    }
    /**
     * 重新加载URL
     */
    open fun reloadUrl(){
        mAgentWeb?.urlLoader?.reload();
    }

}